<?php
/**
 * The control file of action module of ZenTaoPMS.
 *
 * @copyright   Copyright 2009-2015 青岛易软天创网络科技有限公司(QingDao Nature Easy Soft Network Technology Co,LTD, www.cnezsoft.com)
 * @license     ZPL (http://zpl.pub/page/zplv12.html)
 * @author      Chunsheng Wang <chunsheng@cnezsoft.com>
 * @package     action
 * @version     $Id$
 * @link        http://www.zentao.net
 */
class action extends control
{
    /**
     * Trash 
     * 
     * @param  string $type all|hidden 
     * @param  string $orderBy 
     * @param  int    $recTotal 
     * @param  int    $recPerPage 
     * @param  int    $pageID 
     * @access public
     * @return void
     */
    public function trash($type = 'all', $orderBy = 'id_desc', $recTotal = 0, $recPerPage = 20, $pageID = 1)
    {
        /* Save session. */
        $uri = $this->app->getURI(true);
        $this->session->set('productList',     $uri);
        $this->session->set('productPlanList', $uri);
        $this->session->set('releaseList',     $uri);
        $this->session->set('storyList',       $uri);
        $this->session->set('projectList',     $uri);
        $this->session->set('taskList',        $uri);
        $this->session->set('buildList',       $uri);
        $this->session->set('bugList',         $uri);
        $this->session->set('caseList',        $uri);
        $this->session->set('testtaskList',    $uri);
        $this->session->set('docList',         $uri);

        /* Get deleted objects. */
        $this->app->loadClass('pager', $static = true);
        $pager = pager::init($recTotal, $recPerPage, $pageID);

        /* Append id for secend sort. */
        $sort    = $this->loadModel('common')->appendOrder($orderBy);
        $trashes = $this->action->getTrashes($type, $sort, $pager);

        /* Title and position. */
        $this->view->title      = $this->lang->action->trash;
        $this->view->position[] = $this->lang->action->trash;

        $this->view->trashes = $trashes;
        $this->view->type    = $type;
        $this->view->orderBy = $orderBy;
        $this->view->pager   = $pager;
        $this->view->users   = $this->loadModel('user')->getPairs('noletter');
        $this->display();
    }

    /**
     * Undelete an object.
     * 
     * @param  int    $actionID 
     * @access public
     * @return void
     */
    public function undelete($actionID)
    {
        $this->action->undelete($actionID);
        die(js::reload('parent'));
    }

    /**
     * Hide an deleted object. 
     * 
     * @param  int    $actionID 
     * @access public
     * @return void
     */
    public function hideOne($actionID)
    {
        $this->action->hideOne($actionID);
        die(js::reload('parent'));
    }

    /**
     * Hide all deleted objects.
     * 
     * @param  string $confirm 
     * @access public
     * @return void
     */
    public function hideAll($confirm = 'no')
    {
        if($confirm == 'no')
        {
            die(js::confirm($this->lang->action->confirmHideAll, inlink('hideAll', "confirm=yes")));
        }
        else
        {
            $this->action->hideAll();
            die(js::reload('parent'));
        }
    }

    /**
     * Edit comment of a action.
     * 
     * @param  int    $actionID 
     * @access public
     * @return void
     */
    public function editComment($actionID)
    {
        if(trim(strip_tags($this->post->lastComment, '<img>'))) $this->action->updateComment($actionID);
        die(js::locate($this->server->http_referer, 'parent'));
    }
    public function updatealldata(){
        $syncId = $_GET['id']; //回传
        if (empty($syncId)) return;

        header('Content-type: application/json');
        $result['result'] = 'success';
        $result['id'] = $syncId;
        echo json_encode($result);

        $userRes = $this->copyuserinfo();
        $companyRes = $this->copycompanyinfo();
        $userDepartmentRes = $this->copyuserdepartment();

        $address = getenv('address');
        $url = $address . 'ecloud/portal/sync/'.$syncId;
        if (strlen($userRes) > 0 && strlen($companyRes) > 0 && strlen($userDepartmentRes) > 0) {
            if ($userRes == 'success' && $companyRes == 'success' && $userDepartmentRes == 'success') {

                $post_data['result'] = 'success';
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch,CURLOPT_TIMEOUT,60);
                // post数据
                curl_setopt($ch, CURLOPT_POST, 1);
                // post的变量
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
                // curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                //     'Contnet-Length:'.strlen($post_json)
                // ));
                $json = curl_exec($ch);//运行curl
                curl_close($ch);
            } else {
                $post_data['result'] = 'failure';
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch,CURLOPT_TIMEOUT,60);
                // post数据
                curl_setopt($ch, CURLOPT_POST, 1);
                // post的变量
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
                // curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                //     'Contnet-Length:'.strlen($post_json)
                // ));
                $json = curl_exec($ch);//运行curl
                curl_close($ch);
            }
        }

    }
    //1、同步用户信息
    public function copyuserinfo(){
        $clientId = getenv('clientId');
        $clientSecret = getenv('clientSecret');
        $address = getenv('address');

        $url = $address . "ecloud/oapi/token";

        $post_data = array("grantType"=>"client_credentials",
            "clientId"=>$clientId,
            "clientSecret"=>$clientSecret);

        $post_json = json_encode($post_data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_TIMEOUT,60);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_json);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Contnet-Length:'.strlen($post_json)
        ));
        $infojson = curl_exec($ch);//运行curl
        curl_close($ch);

        $infodata = json_decode(trim($infojson),true);
        if (isset($infodata['accessToken']) && !empty($infodata['accessToken'])){
            $getstr = $address . 'ecloud/oapi/user?token='.$infodata['accessToken'];
            //初始化
            $ch = curl_init();
            //设置选项，包括URL
            curl_setopt($ch, CURLOPT_URL, $getstr);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch,CURLOPT_TIMEOUT,60);
            //执行并获取HTML文档内容
            $output = curl_exec($ch);
            //释放curl句柄
            curl_close($ch);

            $userdata = json_decode(trim($output),true);

            if (isset($userdata['entity']) && !empty($userdata['entity'])){

                foreach ($userdata['entity'] as $infodata){
                    $condition['account'] = $infodata['username'];
                    $count = $this->dao->select('*')
                        ->from(TABLE_USER)
                        ->where('account')
                        ->eq($infodata['username'])
                        ->count();

                    $newdata['companyId'] = $infodata['companyId'];
                    $newdata['companyUserId'] = $infodata['companyUserId'];
                    $newdata['email'] = $infodata['email'];
                    $newdata['realname'] = $infodata['employeeName'];
                    $newdata['employeeNo'] = $infodata['employeeNo'];
                    $newdata['phone'] = $infodata['phone'];
                    $newdata['account'] = $infodata['username'];

                    //用户权限,默认同步的全部用户权限为11guest
                    $usergroup['group'] = 0;
                    $usergroup['account'] = $infodata['username'];
                    $u_group = $this->dao->select('*')->from(TABLE_USERGROUP)->where('account')->eq($infodata['username'])->count();
                    if ($u_group <= 0){
                        $this->dao->insert(TABLE_USERGROUP)->data($usergroup)->exec();
                    }else{
                        $this->dao->update(TABLE_USERGROUP)
                            ->set('`group`')
                            ->eq(0)
                            ->where('account')
                            ->eq($infodata['username'])->exec();
                    }
                    if ($count <= 0){

                        $this->dao->insert(TABLE_USER)->data($newdata)->exec();

                    }else{

                        $this->dao->update(TABLE_USER)
                            ->data($newdata)
                            ->where('account')
                            ->eq($infodata['username'])
                            ->exec();
                    }

                }
                $tempres = 'success';
                return $tempres;
            }else{
                $tempres = '用户信息同步失败,user->entity为空';
                return $tempres;
            }
        }else{
            $tempres = '用户信息同步失败,token无效';
            return $tempres;
        }

    }
    //2、同步公司部门架构
    public function copycompanyinfo(){

        $clientId = getenv('clientId');
        $clientSecret = getenv('clientSecret');
        $address = getenv('address');

        $url = $address . "ecloud/oapi/token";

        $post_data = array("grantType"=>"client_credentials",
            "clientId"=>$clientId,
            "clientSecret"=>$clientSecret);

        $post_json = json_encode($post_data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_TIMEOUT,60);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_json);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Contnet-Length:'.strlen($post_json)
        ));
        $infojson = curl_exec($ch);//运行curl
        curl_close($ch);

        $infodata = json_decode(trim($infojson),true);
        if (isset($infodata['accessToken']) && !empty($infodata['accessToken'])){
            $getstr = $address . 'ecloud/oapi/department?token='.$infodata['accessToken'];
            //初始化
            $ch = curl_init();
            //设置选项，包括URL
            curl_setopt($ch, CURLOPT_URL, $getstr);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch,CURLOPT_TIMEOUT,60);
            //执行并获取HTML文档内容
            $output = curl_exec($ch);
            //释放curl句柄
            curl_close($ch);

            $userdata = json_decode(trim($output),true);
            if (isset($userdata['entity']) && !empty($userdata['entity'])){

                $this->updateCompany($userdata['entity']);

                $tempres = 'success';
                return $tempres;
            }else{
                $tempres = '公司部门架构同步失败,user->entity为空';
                return $tempres;
            }
        }else{
            $tempres = '公司部门架构同步失败,token无效';
            return $tempres;
        }

    }
    //3、同步用户对应部门信息
    public function copyuserdepartment(){

        $clientId = getenv('clientId');
        $clientSecret = getenv('clientSecret');
        $address = getenv('address');

        $url = $address . "ecloud/oapi/token";

        $post_data = array("grantType"=>"client_credentials",
            "clientId"=>$clientId,
            "clientSecret"=>$clientSecret);

        $post_json = json_encode($post_data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_TIMEOUT,60);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_json);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Contnet-Length:'.strlen($post_json)
        ));
        $infojson = curl_exec($ch);//运行curl
        curl_close($ch);

        $infodata = json_decode(trim($infojson),true);
        if (isset($infodata['accessToken']) && !empty($infodata['accessToken'])) {
            $getstr = $address . 'ecloud/oapi/user_department?token=' . $infodata['accessToken'].'&operation=sync';
            //初始化
            $ch = curl_init();
            //设置选项，包括URL
            curl_setopt($ch, CURLOPT_URL, $getstr);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            //执行并获取HTML文档内容
            $output = curl_exec($ch);
            //释放curl句柄
            curl_close($ch);

            $userdata = json_decode(trim($output), true);
            if (isset($userdata['entity']) && !empty($userdata['entity'])){

                foreach ($userdata['entity'] as $val){

//                    $newdata['dept'] = $val['departmentId'];
                    $this->dao->update(TABLE_USER)
                        ->set('dept')
                        ->eq($val['departmentId'])
                        ->where('account')
                        ->eq($val['username'])->exec();

                    if ($val['roleType'] == 'adm'){
                        $olddata = $this->dao->select('admins')->from(TABLE_COMPANY)->orderBy('id')->limit(1)->fetch('admins');
                        $deleteadmin = ',' . $val['username'] . ',';
                        if (strpos($olddata, $deleteadmin) === false) {
                            $newadmins = $olddata . $val['username'] . ',';

                            $this->dao->update(TABLE_COMPANY)
                                ->set('admins')
                                ->eq($newadmins)
                                ->where('id')
                                ->eq(1)->exec();
                        }

                        //用户权限-管理员权限
                        $usergroup['group'] = 1;
                        $usergroup['account'] = $val['username'];
                        $u_group = $this->dao->select('*')->from(TABLE_USERGROUP)->where('account')->eq($val['username'])->count();
                        if ($u_group <= 0){
                            $this->dao->insert(TABLE_USERGROUP)->data($usergroup)->exec();
                        }else{
                            $this->dao->update(TABLE_USERGROUP)
                                ->set('`group`')
                                ->eq(1)
                                ->where('account')
                                ->eq($val['username'])->exec();
                        }
                    }else{
                        $olddata = $this->dao->select('admins')->from(TABLE_COMPANY)->orderBy('id')->limit(1)->fetch('admins');
                        $deleteadmin = ',' . $val['username'] . ',';
                        if (strpos($olddata, $deleteadmin) !== false){
                            $newadmins = str_replace($deleteadmin, ',', $olddata);
                            $this->dao->update(TABLE_COMPANY)
                                ->set('admins')
                                ->eq($newadmins)
                                ->where('id')
                                ->eq(1)->exec();

                        }
                        //用户权限-研发权限权限
                        $usergroup['group'] = 2;
                        $usergroup['account'] = $val['username'];
                        $u_group = $this->dao->select('*')->from(TABLE_USERGROUP)->where('account')->eq($val['username'])->count();
                        if ($u_group <= 0){
                            $this->dao->insert(TABLE_USERGROUP)->data($usergroup)->exec();
                        }else{
                                $this->dao->update(TABLE_USERGROUP)
                                    ->set('`group`')
                                    ->eq(2)
                                    ->where('account')
                                    ->eq($val['username'])->exec();


                        }
                    }

                }

                $tempres = 'success';
                return $tempres;
            }else{
                $tempres = '用户对应部门信息同步失败,user->entity为空';
                return $tempres;
            }
        }else{
            $tempres = '用户对应部门信息同步失败,token无效';
            return $tempres;
        }

    }

    /*递归遍历*/
    private function updateCompany($infoArr){

        $count = $this->dao->select('*')
            ->from(TABLE_DEPT)
            ->where('id')
            ->eq($infoArr['departmentId'])
            ->count();

        $newdata['id'] = $infoArr['departmentId'];
        $newdata['parent'] = $infoArr['parentId'] ? $infoArr['parentId'] : 0;
        $newdata['name'] = $infoArr['nodeName'];

        $parent_dept = $this->dao->findById($newdata['parent'])->from(TABLE_DEPT)->fetch();
        if($parent_dept)
        {
            $grade      = $parent_dept->grade + 1;
            $parentPath = $parent_dept->path;
        }
        else
        {
            $grade      = 1;
            $parentPath = ',';
        }

        $newdata['grade'] = $grade;
        $newdata['path'] = $parentPath . $newdata['id'] . ",";

        if ($count <= 0){

            $this->dao->insert(TABLE_DEPT)->data($newdata)->exec();

        }else{
            $this->dao->update(TABLE_DEPT)
                ->data($newdata)
                ->where('id')
                ->eq($infoArr['departmentId'])
                ->exec();
        }

        if (!is_array ($infoArr['children']) || empty($infoArr['children'])) return;

        foreach ($infoArr['children'] as $val )
        {
            $this->updateCompany($val);

        }

    }


}
